package com.type.service;

import java.io.File;
import java.util.Date;

import javax.servlet.http.HttpSession;

import org.apache.commons.io.FileUtils;
import org.springframework.web.multipart.MultipartFile;

public class FileUtil {
	
	public static String getRealFileName(int no, HttpSession session){
		return session.getServletContext().getRealPath("/img/type/typeOne")+"/image"+no+".jpg";
	}
	
	public static String getImageUrl(int no){
		return "img/type/typeOne/image"+no+".jpg?"+new Date().getTime();
	}
	public static void validateFile(MultipartFile image){
		if(!image.getContentType().equals("image/jpeg")){
			throw new FileUploadException("Your file : " + image.getContentType() + ". Only JPG image accepted");
		}
	}
	public static void saveFile(String fileName, MultipartFile image){
		if(fileName!=""){
			try{
				File file = new File(fileName);
				if(file.exists()){
				removeFile(fileName);
			}
			FileUtils.writeByteArrayToFile(file, image.getBytes());
			}catch(Exception e){
				System.out.println(e.getStackTrace());
			}
		}
	}
	public static void removeFile(String fileName){
		try{
			File file = new File(fileName);
			if(file.exists()){
				file.delete();
			}
		}catch(Exception e){
			System.out.println(e.getStackTrace());
		}
	}
	
}
